const R = require('@/models/Response')
const { ERROR_USER_CODE, ERROR_SYSTEM_CODE } = require('@/constants/errorCode')
const User = require('@/models/userModel')
const Paper = require('@/models/paperModel')
const UserActiveExam = require('@/models/userActiveExam')

/**
 * @description token验证的中间件
 * @param {boolean} required 是否需要token才能调通此接口
 * @param {boolean} isReflesh 是否验证刷新token
 * @returns
 */
module.exports.verifyHasActive = function () {
  return async (ctx, next) => {
    const { id } = ctx.user
    const { paperId } = ctx.query
    const user = await User.findByPk(BigInt(id))
    if (+user.roleId === 1) {
      await next()
    } else {
      // 判断用户是否已经激活该试卷
      if (paperId == undefined) {
        ctx.body = R.error(ERROR_SYSTEM_CODE.PERMISSION_ERROR)
        return
      }
      const paper = await Paper.findByPk(BigInt(paperId))
      if (!paper) {
        ctx.body = R.error(ERROR_SYSTEM_CODE.PERMISSION_ERROR)
        return
      }
      // 找到examId，
      const one = await UserActiveExam.findOne({
        where: {
          userId: BigInt(id),
          examId: BigInt(paper.examId)
        }
      })

      if (!one) {
        ctx.body = R.error(ERROR_SYSTEM_CODE.PERMISSION_ERROR)
        return
      }

      await next()
    }
  }
}
